package com.chao.wind3j.base.config.shiroConfig.advisor;

import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.aop.AuthorizingAnnotationHandler;

import java.lang.annotation.Annotation;

public class RolesHandler extends AuthorizingAnnotationHandler {
  public RolesHandler() {
    super(CCRoles.class);
  }
  @Override
  public void assertAuthorized(Annotation a) throws AuthorizationException {
    if (a instanceof CCRoles) {
      var annotation = (CCRoles) a;
      var roles = annotation.value();
      var subject = getSubject();
      if (roles.length == 1) {
        subject.checkRole(roles[0]);
        return;
      }
      // 多个权限，有一个就通过
      boolean hasAtLeastOnePermission = false;
      for (String role : roles) {
        if (subject.hasRole(role)) {
          hasAtLeastOnePermission = true;
          break;
        }
      }
      if (!hasAtLeastOnePermission) {
        subject.checkRole(roles[0]);
      }
    }
  }
}
